package com.uni.controller;

import com.uni.entity.Dto;
import com.uni.entity.ShopImages;
import com.uni.service.ShopImagesService;
import com.uni.util.DtoUtil;
import com.uni.util.FastDFSClientUtils;
import com.uni.util.FileUpload;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 前端图片接口
 */
@Slf4j
@RestController
@RequestMapping("img")
@CrossOrigin
public class ShopImagesController {

    @Autowired
    private ShopImagesService shopImagesService;

    /**
     * 按类型获取图片列表
     * @param type
     * @return
     */
    @GetMapping("/get/{type}")
    public Dto getImageByType(@PathVariable("type") Integer type){
        List<ShopImages> shopImages = new ArrayList<>();
        if (type >= 0) {
            ShopImages image = new ShopImages(type);
            shopImages = shopImagesService.queryAll(image);
        }
        return DtoUtil.returnDataSuccess(shopImages);
    }
    //上传图片
    @PostMapping("upload")
    public Dto uploadImg(MultipartFile file){
        if (file.isEmpty()) {
            return DtoUtil.returnFail("文件夹为空","500");
        }
        try {
                return DtoUtil.returnSuccess("上传成功",
                        FastDFSClientUtils.upload(file.getBytes(),file.getOriginalFilename())
                );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return DtoUtil.returnFail("上传失败，请联系管理员","500");
    }

    /**
     * 收集埋点数据
     * @param data
     * @return
     */
    @PostMapping("/log")
    public Dto log(@RequestBody String data){
        log.info("收集的数据: " + data);
        return DtoUtil.returnSuccess();
    }

    @GetMapping("del/{id}")
    public  Dto del(@PathVariable("ids") List<Integer> ids){
        if (shopImagesService.deleteById(ids)){
            return DtoUtil.returnDataSuccess("批量删除成功!");
        }else{
            return  DtoUtil.returnFail("批量删除失败!","5001");
        }
    }




}
